/**
 * \file misc.c
 **/

#include <stdio.h>
#include "mem.h"
#include "misc.h"

int r_misc_loadfile(char* filename, char** buffer, uint32_t* size)
{
  int file_size;
  int rv = R_SUCCESS;
  char* file_buffer;
  FILE *f = fopen(filename, "rb");
  if (f == NULL)
  {
    return R_CANT_OPEN_RESOURCE;
  }

  /* Get the size of the file. */
  if (fseek(f, 0, SEEK_END)){
    rv = R_IO_ERROR;
    goto cleanup;
  }
  file_size = ftell(f);
  if (fseek(f, 0, SEEK_SET)){
    rv = R_IO_ERROR;
    goto cleanup;
  }

  /* Check the file size. */
  if (file_size < 0){
    rv = R_IO_ERROR;
    goto cleanup;
  }
  if (file_size == 0){
    *size = 0;
    *buffer = NULL;
    rv = R_SUCCESS;
    goto cleanup;
  }

  /* Allocate buffer for file contents. */
  file_buffer = (char *) r_mem_malloc(file_size);
  if (file_buffer == NULL){
    rv = R_NO_MEM;
    goto cleanup;
  }

  /* Read the file in. */
  if (file_size != fread(file_buffer, sizeof(char), file_size, f))
  {
    r_mem_free(file_buffer);
    rv = R_IO_ERROR;
    goto cleanup;
  }

  cleanup:
  fclose(f);
  return rv;
}

/* TODO: This implementation is extremely inefficient. Replace with better */
uint32_t r_misc_power2(uint32_t min)
{
  uint32_t num = 8;
  while (num < min) num *= 2;
  return num;
}
